using System;
using System.Collections.Generic;
using System.Linq;
using System.Linq.Expressions;

namespace EntityFramework.ServiceLayer
{
    public abstract class EntityToDtoMapper<TEntity, TDto>
    {
        public abstract TDto ToDto(TEntity entity);

        public TDto[] ToDtos(IEnumerable<TEntity> entities)
        {
            return entities != null ? entities.Select(entity => ToDto(entity)).ToArray() : null;
        }

        public virtual Dictionary<string, string> GetPropertyMappings()
        {
            throw new NotImplementedException(string.Format("GetPropertyMappings should be implemented on {0}.", GetType().Name));
        }

        public string GetEntityPropertyName(string dtoPropertyName)
        {
            if (dtoPropertyName == null)
            {
                return GetDefaultPropertyName(); 
            }
            else
            {
                var propertyMapping = GetPropertyMappings()[dtoPropertyName];

                if (propertyMapping == null)
                {
                    //only return the names that are different.
                    return dtoPropertyName;
                    //throw new InvalidOperationException(string.Format("No property mapping for {0} found in {1}.", dtoPropertyName, GetType().Name));
                }

                return propertyMapping;
            }
        }

        private string GetDefaultPropertyName()
        {
            if (GetPropertyMappings().Count > 0)
            {
                return GetPropertyMappings().Values.ToList()[0];
            } 
            else
            {
                throw new InvalidOperationException(string.Format("No property mappings found for {0}.", GetType().Name));
            }
        }
    }
}